import 'package:flutter/material.dart';
import 'package:lazy_load_indexed_stack/lazy_load_indexed_stack.dart';
import 'package:learning/constants/app_strings.dart';
import 'package:learning/pages/main_tab/account/account_page.dart';
import 'package:learning/pages/main_tab/account/account_page_logic.dart';
import 'package:learning/pages/main_tab/main_tab_logic.dart';
import 'package:provider/provider.dart';

class MainTab extends StatefulWidget {
  const MainTab({super.key});

  @override
  _MainTabState createState() => _MainTabState();
}

class _MainTabState extends State<MainTab> {
  late List<Widget> _pages;

  @override
  void initState() {
    super.initState();
    _pages = [
      Container(color: Colors.red),
      Container(color: Colors.green),
      Container(color: Colors.blue),
      ChangeNotifierProvider(
        create: (context) => AccountPageLogic(),
        child: const AccountPage(),
      ),
    ];

    context.read<MainTabLogic>().init();
  }

  Widget _buildPageView(BuildContext context) {
    return Selector<MainTabLogic, int>(
        selector: (context, logic) => logic.mainTabIndex,
        builder: (context, index, child) {
          return LazyLoadIndexedStack(index: index, children: _pages);
        });
  }

  Widget _buildBottomNavigationBar(BuildContext context) {
    const bottomTabs = <BottomNavigationBarItem>[
      BottomNavigationBarItem(
        icon: Icon(Icons.home),
        label: AppStrings.home,
      ),
      BottomNavigationBarItem(
        icon: Icon(Icons.grade_rounded),
        label: AppStrings.category,
      ),
      BottomNavigationBarItem(
        icon: Icon(Icons.menu_book),
        label: AppStrings.learning,
      ),
      BottomNavigationBarItem(
        icon: Icon(Icons.person),
        label: AppStrings.profile,
      ),
    ];
    return Selector<MainTabLogic, int>(
        selector: (context, logic) => logic.mainTabIndex,
        builder: (context, index, child) {
          return BottomNavigationBar(
            selectedItemColor: Theme.of(context).colorScheme.primary,
            unselectedItemColor: Theme.of(context).colorScheme.secondary,
            type: BottomNavigationBarType.fixed,
            currentIndex: index,
            onTap: (index) {
              context.read<MainTabLogic>().setMainTabIndex(index);
            },
            items: bottomTabs,
          );
        });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: _buildPageView(context),
      bottomNavigationBar: _buildBottomNavigationBar(context),
    );
  }
}
